package com.amokgames.tictactoe;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;



import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BTClient extends Service {
	public static final String START= "org.sacgtug.bt1.BTClient.START";
	public static final String STOP= "org.sacgtug.bt1.BTClient.STOP";
	public static final String EXTRA_SERVICE_NAME= "serviceName";
	
	private String serviceName;
	private BluetoothAdapter bta;
	private BluetoothSocket socket;

	@Override
	public void onCreate() {
		super.onCreate();
		//TODO: ???
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("bt1", "BTClient service start");
		serviceName= intent.getStringExtra(EXTRA_SERVICE_NAME);
		byte[] nameHash= null;
		try {
			nameHash= Util.SHA1(serviceName);
		} catch (UnsupportedEncodingException uee) { /*ignore*/
		} catch (NoSuchAlgorithmException nsae) { /*ignore*/ }

		UUID uuid= UUID.nameUUIDFromBytes(nameHash);
		bta= BluetoothAdapter.getDefaultAdapter();
		BluetoothDevice serverDevice= null;
		//TODO: choose server via activity by presenting list, pass as string extra here
		for (BluetoothDevice d : bta.getBondedDevices()) {
			Log.i("BT", d.getName());
			if (d.getName().equals("akDroid")) serverDevice= d;
		}
		try {			
			socket= serverDevice.createRfcommSocketToServiceRecord(uuid);
			Log.i("bt1", "BTServer open socket, name="+ serviceName +", uuid="+ uuid.toString());
		} catch (IOException ioe) {
			//TODO: ???
		}
		return START_NOT_STICKY;
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		//TODO: ???
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i("bt1", "BTClient service end");
	}
}
